package com.yyw.mcar.base;

import android.content.Context;
import android.support.v4.app.FragmentActivity;
import android.widget.Toast;

import java.util.Stack;

import cn.shinsoft.app.Application;

/**
 * @Title: 基础的application类
 * @Description: 功能类
 * @Author: wanghaixiao
 * @Date: 2016/9/21
 * @Version:1.0.2
 */
public class BaseApplication extends Application {

    private static BaseApplication baseApp;
    private static Context context;
    private static Stack<FragmentActivity> activityList;

    @Override
    public void onCreate() {
        super.onCreate();

        super.onCreate();
        baseApp = this;
        context = this;

    }

    public static BaseApplication getInstance() {
        return baseApp;
    }

    /**
     * 结束当前Activity（堆栈中最后一个压入的）
     */
    public void finishActivity() {
        FragmentActivity activity = activityList.lastElement();
        finishActivity(activity);
    }

    /**
     * 结束指定的Activity
     */
    public void finishActivity(FragmentActivity activity) {
        if (activity != null) {
            if (activityList != null) {
                activityList.remove(activity);
            }
            activity.finish();
            activity = null;
        }
    }

    // 添加Activity到容器中
    public static void addActivity(FragmentActivity activity) {

        if (activityList == null) {
            activityList = new Stack<FragmentActivity>();
        }

        activityList.add(activity);
    }

    // 遍历所有Activity并finish
    public static void exit() {
        try {
            if (activityList != null && activityList.size() > 0) {
                for (FragmentActivity activity : activityList) {
                    activity.finish();
                }
            }
            System.exit(0);
        } catch (Exception e) {
            Toast.makeText(context, e.toString(), Toast.LENGTH_LONG).show();
        }

    }

}
